﻿using TbShop.Business.Components;
using TbShop.Data.Components;
using TbShop.Entity;
using TbShop.Web.Helpers;
using TbShop.Web.Infrastructure;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using Microsoft.AspNet.Identity;
using TbShop.Web.Infrastructure.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using HeinQi.Framework.Common;
using TbShop.Web.Areas.Admin.Models;

namespace TbShop.Web.Areas.Admin.Controllers
{
    public class AdministratorController : BaseController
    {
        private AspNetRoleBC roleBC = new AspNetRoleBC();
        public UserManager<ApplicationUser> UserManager { get; private set; }

        public AdministratorController()
            : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {
        }

        public AdministratorController(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }

        public ActionResult Index()
        {
            var roles = roleBC.GetAll();
            ViewBag.RoleList = JsonConvert.SerializeObject(roles.Select(x => new { value = x.Id, text = x.Name }));
            return View();
        }

        /// <summary>
        /// 获取管理员列表
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageNumber"></param>
        /// <returns></returns>
        public string GetUserList(int pageSize = 0, int pageNumber = 0)
        {
            var name = Request.QueryString["name"];
            var source = UserManager.Users.OrderByDescending(p => p.Id).ToList();
            if (!string.IsNullOrWhiteSpace(name))
            {
                source = source.Where(a => a.Name.Contains(name) || a.UserName.Contains(name)).ToList();
            }
            var pagedList = new PagedList<ApplicationUser>(source, pageNumber, pageSize);
            var list = new List<AdministratorDetailViewModel>();
            foreach (var item in pagedList)
            {
                list.Add(new AdministratorDetailViewModel
                {
                    Id = item.Id,
                    HeadPortrait = item.HeadPortrait,
                    UserName = item.UserName,
                    Name = item.Name,
                    Address = item.Address,
                    PhoneNumber = item.PhoneNumber,
                    LastLoginTime = item.LastLoginTime,
                    LastLoginIP = item.LastLoginIP,
                    LoginCount = item.LoginCount,
                    CreatedBy = item.CreatedBy,
                    CreatedDate = item.CreatedDate,
                    RoleId = item.RoleId
                });
            }
            var meta = pagedList.GetMetaData();
            var counts = meta.TotalItemCount;
            return JsonConvert.SerializeObject(new { total = counts, rows = list });
        }
        public ActionResult ChangePassword()
        {
            return View(new ManageUserViewModel());
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ChangePassword(ManageUserViewModel model)
        {
            var userId = User.Identity.GetUserId();
            if (ModelState.IsValid)
            {
                var result = UserManager.ChangePassword(userId, model.OldPassword, model.NewPassword);
                if (result.Succeeded)
                {
                    var findUser = UserManager.Users.Where(x => x.Id == userId).SingleOrDefault();
                    OperationLogHelper.SaveOperationLog(AdminId, "修改", "管理员", "登录密码", userId);
                    SendMessage("密码修改成功", Constants.MessageType.Success);
                    return RedirectToAction("Login", "Account");
                }
                else
                {
                    SendMessage("旧密码错误", Constants.MessageType.Warning);
                }
            }
            SendMessage("密码修改失败", Constants.MessageType.Warning);
            return View(model);
        }
        /// <summary>
        /// 修改管理员信息页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(string id = "")
        {
            ApplicationUser model = null;
            var roleid = "";
            if (!string.IsNullOrEmpty(id))
            {
                model = UserManager.FindById(id);
                var userRole = model.Roles;
                if (userRole.Any())
                {
                    roleid = userRole.FirstOrDefault().RoleId;
                }
            }
            else
            {
                model = new ApplicationUser();
                model.Id = string.Empty;
            }
            var roles = roleBC.GetAll();
            var rolesList = DropdownHelper.ConvertToSelectListItem(from c in roles
                                                                   select new
                                                                   {
                                                                       Value = c.Name,
                                                                       Key = c.Id
                                                                   }, false);
            var resultModel = new AdministratorDetailViewModel
            {
                Id = model.Id,
                Name = model.Name,
                PhoneNumber = model.PhoneNumber,
                UserName = model.UserName,
                Password = model.PasswordHash,
                RolesList = rolesList,
                RoleId = roleid,
                Address = model.Address,
                OldRoleId = roleid,
                HeadPortrait = model.HeadPortrait,
                LastLoginTime = model.LastLoginTime,
                LastLoginIP = model.LastLoginIP,
                LoginCount = model.LoginCount,
                IsDeleted = model.IsDeleted,
                PasswordMD5 = model.PasswordMD5,
                CreatedDate = model.CreatedDate,
                CreatedBy = model.CreatedBy
            };

            return View(resultModel);
        }

        /// <summary>
        /// 验证账号是否重复
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool HasUserName(string userName, string id)
        {
            bool hasUserName = false;
            var users = UserManager.Users.Where(u => u.UserName == userName);
            if (users.Any())
            {
                if (users.FirstOrDefault().Id != id)
                {
                    hasUserName = true;
                }
            }
            return hasUserName;
        }

        /// <summary>
        /// 修改管理员信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(AdministratorDetailViewModel model)
        {
            if (!string.IsNullOrEmpty(model.Id))
            {
                ModelState.Remove("Password");
                ModelState.Remove("PasswordConfirm");
            }
            else
            {
                if (HasUserName(model.UserName, model.Id))
                {
                    ModelState.AddModelError("UserNameDuplication", "登录账号不能重复");
                }
            }
            if (ModelState.IsValid)
            {
                IdentityResult res = null;
                var newFile = "";
                if (Request.Files.Count > 0)
                {
                    var file = this.Request.Files["shortcutImg"];
                    if (file != null && file.FileName.Length > 0)
                    {
                        var filePath = StaticWords.UploadFolder.Avatar;
                        DirectoryHelper.MarkDir(filePath);
                        var newFileName = UnityHelper.GetRandomNumber() + "." + file.FileName.Split('.').Last();
                        newFile = filePath + newFileName;
                        file.SaveAs(Server.MapPath(newFile));
                    }
                }
                if (string.IsNullOrEmpty(model.Id))
                {
                    model.Id = Guid.NewGuid().ToString();
                    var newUser = new ApplicationUser
                    {
                        Id = model.Id,
                        UserName = model.UserName,
                        HeadPortrait = newFile,
                        Name = model.Name,
                        Address = model.Address,
                        RoleId = model.RoleId,
                        PhoneNumber = model.PhoneNumber,
                        CreatedDate = DateTime.Now,
                        CreatedBy = User.Identity.Name,
                        IsDeleted = false
                    };
                    newUser.PasswordMD5 = EncryptHelper.MD5ToBase64(model.Password);
                    var add = new IdentityUserRole() { RoleId = model.RoleId, UserId = model.Id };
                    newUser.Roles.Add(add);
                    res = UserManager.Create(newUser, model.Password);
                }
                else
                {
                    var currentUser = UserManager.FindById(model.Id);
                    currentUser.PhoneNumber = model.PhoneNumber;
                    if (!string.IsNullOrWhiteSpace(model.OldRoleId))
                    {
                        currentUser.Roles.Remove(currentUser.Roles.First());
                    }
                    currentUser.Roles.Add(new IdentityUserRole() { UserId = model.Id, RoleId = model.RoleId });
                    if (Request.Files.Count > 0)
                    {
                        //if (!string.IsNullOrWhiteSpace(model.HeadPortrait))
                        //{
                        //    System.IO.File.Delete(Server.MapPath(model.HeadPortrait));
                        //}
                        if (!string.IsNullOrWhiteSpace(newFile))
                        {
                            currentUser.HeadPortrait = newFile;
                        }
                    }
                    else
                    {
                        currentUser.HeadPortrait = model.HeadPortrait;
                    }
                    currentUser.Name = model.Name;
                    currentUser.RoleId = model.RoleId;
                    currentUser.Address = model.Address;
                    res = UserManager.Update(currentUser);
                }
                if (res.Succeeded)
                {
                    AdminHelper.UserDatas = null;
                    OperationLogHelper.SaveOperationLog(AdminId, "修改", "管理员", "", model.Id);
                    SendMessage("保存成功", Constants.MessageType.Success);
                    return RedirectToAction("Index");
                }
            }
            SendMessage("保存失败", Constants.MessageType.Warning);
            var roles = roleBC.GetAll();
            var rolesList = DropdownHelper.ConvertToSelectListItem(from c in roles
                                                                   select new
                                                                   {
                                                                       Value = c.Name,
                                                                       Key = c.Id
                                                                   }, false);
            model.RolesList = rolesList;
            return View(model);
        }
        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(string id)
        {
            var findUser = UserManager.FindById(id);
            UserManager.Delete(findUser);
            AdminHelper.UserDatas = null;
            OperationLogHelper.SaveOperationLog(AdminId, "删除", "管理员", "", id);
            SendMessage("管理员删除成功", Constants.MessageType.Success);
            return RedirectToAction("Index");
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetPassword(string id)
        {
            var findUser = UserManager.FindById(id);
            var password = HeinQi.Framework.Common.SystemParameterHelper.GetSystemParameter<string>(Constants.SystemParameterKeys.AdministratorDefaultPassword);
            UserManager.RemovePassword(id);
            UserManager.AddPassword(id, password);
            UserManager.Update(findUser);
            OperationLogHelper.SaveOperationLog(User.Identity.Name, "修改", "重置了管理员的登录密码，编号为【" + id + "】");
            SendMessage("密码重置成功", Constants.MessageType.Success);
            return RedirectToAction("Index");
        }
    }
}